﻿using System;
using Eneta.Portal.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Events
{
    public class EventCommentsListFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var web = properties.Feature.Parent as SPWeb;
            if (web == null)
                web = ((SPSite)properties.Feature.Parent).RootWeb;

            if (!PublishingWeb.IsPublishingWeb(web))
                throw new Exception("Current web is not publishing web!");

            web.AllowUnsafeUpdates = true;

            var pagesListName = PublishingWeb.GetPagesListName(web);
            var pagesList = web.Lists[pagesListName];
            var list = web.Lists["Comments"];

            if (!list.HasField("Event"))
            {
                list.Fields.AddLookup("Event", pagesList.ID, true);
                var field = list.Fields["Event"] as SPFieldLookup;
                field.LookupField = pagesList.Fields[SPBuiltInFieldId.Title].InternalName;
                field.Update(true);
                list.Update();
            }

            list = web.Lists["EventRegistrations"];
            if (!list.HasField("Event"))
            {
                list.Fields.AddLookup("Event", pagesList.ID, true);
                var field = list.Fields["Event"] as SPFieldLookup;
                field.LookupField = pagesList.Fields[SPBuiltInFieldId.Title].InternalName;
                field.Update(true);
                list.Update();
            }

            web.Update();
        }
    }
}
